/*
    Coder : Dzlua
    Email : 505544956@qq.com
    Time  : 2017/08/03
*/
extern "C" {
#include <sdl/SDL.h>
#include <sdl/SDL_TTF.h>
#include <sdl/SDL_image.h>
}

#include "dialog.h"

#include <dzlua/dzlua.h>
using namespace dzlua;

bool Init();

int main(int argc, int *argv[]) {
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to initialize SDL2: %s", SDL_GetError());
        return false;
    }

    if (TTF_Init() != 0){
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to initialize SDL2_TTF: %s", TTF_GetError());
        return false;
    }

    if (IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG) == 0){
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to initialize SDL2_image: %s", IMG_GetError());
        return false;
    }

    bool bret = Init();

    IMG_Quit();

    if (TTF_WasInit() == 0){
        TTF_Quit();
    }

    if (SDL_WasInit(SDL_INIT_EVERYTHING)) {
        SDL_Quit();
    }

    return bret ? 0 : -1;
}

bool Init() {
    SDL_Window *pWin = nullptr;
    SDL_Renderer *pRen = nullptr;
    TTF_Font *pFont = nullptr;
    if ( -1 == SDL_CreateWindowAndRenderer(640, 480, SDL_WINDOW_SHOWN, &pWin, &pRen) ) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "error SDL_CreateWindowAndRenderer: %s", SDL_GetError());
        goto error;
    }

    {
        auto cur_dir = FilePath::MoudlePath();
        cur_dir->append("simhei.ttf");
        pFont = TTF_OpenFont(cur_dir->string().c_str(), 20);
        if (!pFont) {
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "error TTF_OpenFont: %s", TTF_GetError());
            goto error;
        }
    }


    SDL_Event evt;
    while (SDL_WaitEvent(&evt)) {
        if (evt.type == SDL_QUIT) break;
        if (evt.type == SDL_KEYDOWN) {
            switch (evt.key.keysym.sym) {
                case SDLK_m: {
                    auto ret = ShowDialog(pWin, pFont, "title", "hello dzlua.", BT_TYPE_OK);

                } break;
            }
        }
    }
error:
    //
    if (pRen) SDL_DestroyRenderer(pRen);
    if (pWin) SDL_DestroyWindow(pWin);
    return true;
}
